package cn.damong.utils.common;

import java.net.Inet6Address;
import java.net.InetAddress;
import java.net.NetworkInterface;
import java.util.ArrayList;
import java.util.Enumeration;
import java.util.List;
import java.util.regex.Pattern;

import org.apache.commons.lang.StringUtils;


/**
 * IP工具类
 * 
 * @author CodingPanda
 * @2019年5月15日 下午11:13:43
 *
 */
public class IPUtil {

    private static List<InetAddress> localAddressList;

    /**
     * 获取本地IP(非局域网IP，非IPV6 IP)
     * 
     * @return
     */
    public static String getLocalIP() {
        return getLocalIP(false);
    }

    /**
     * 获取本地IP
     * 
     * @param isInter 是否局域网IP
     *            
     * @return
     */
    public static String getLocalIP(boolean isInter) {
        if (localAddressList == null) {
            localAddressList = getLocalAddresses();
        }
        String localIP = "";
        for (InetAddress ia : localAddressList) {
            String ip = ia.getHostAddress();

            if (ia instanceof Inet6Address || ip.startsWith("127")) {
                continue;
            }

            if (StringUtils.isBlank(localIP)) {
                localIP = ip;
            }
            if (isInter && ip.startsWith("192.")) {
                return ip;
            }
            if (!isInter && !ip.startsWith("192.")) {
                return ip;
            }
        }
        return localIP;
    }

    /**
     * 判断字符串是否IP地址
     * 
     * @param address IP地址字符串
     * @return
     */
    public static boolean isIP(String address) {
        Pattern ipPattern = Pattern.compile("\\b(?:[0-9]{1,3}\\.){3}[0-9]{1,3}\\b");
        return ipPattern.matcher(address).matches();
    }

    /**
     * 获取本地IP地址
     * 
     * @return
     */
    public static List<InetAddress> getLocalAddresses() {
        if (localAddressList == null) {
            localAddressList = new ArrayList<InetAddress>();
            try {
                Enumeration<NetworkInterface> interfaces = NetworkInterface.getNetworkInterfaces();
                while (interfaces != null && interfaces.hasMoreElements()) {
                    NetworkInterface interfaceN = interfaces.nextElement();
                    Enumeration<InetAddress> ienum = interfaceN.getInetAddresses();
                    while (ienum.hasMoreElements()) {
                        InetAddress ia = ienum.nextElement();
                        localAddressList.add(ia);
                    }
                }
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
        return localAddressList;
    }

    /**
     * ip字符串转整数 ip是.分割的整数字符串,按照r进制转十进制的规律,按权相加求和,这里的权是256.
     * 
     * @param ip
     * @return
     */
    public static int ip2Int(String ip) {
        if (null == ip || "".equals(ip.trim()) || !checkIP(ip)) {
            return 0;
        }
        String[] ipStrs = ip.split("\\.");// 分割ip
        int result = 0;
        for (int i = 0; i < 4; i++) {
            Integer ipSubInteger = Integer.parseInt(ipStrs[i]);
            if (ipSubInteger > 255) {// 正则验证不能为负数
                result = 0;
                break;
            }
            result += (ipSubInteger << (24 - i * 8));
        }
        return result;
    }

    /* 正则验证ip */
    private static boolean checkIP(String ip) {
        return ip.matches("\\d{1,3}(\\.\\d{1,3}){3}");
    }

    /**
     * int类型IP转换成字符串类型IP
     * 
     * @param ip
     * @return
     */
    public static String int2Ip(int ip) {
        StringBuilder builder = new StringBuilder(String.valueOf(ip >>> 24));
        builder.append(".");
        builder.append(String.valueOf((ip & 0X00FFFFFF) >>> 16));
        builder.append(".");
        builder.append(String.valueOf((ip & 0X0000FFFF) >>> 8));
        builder.append(".");
        builder.append(String.valueOf(ip & 0X000000FF));
        return builder.toString();
    }

}
